﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Maticsoft.BLL;
using Maticsoft.Model;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Configuration;

namespace Maticsoft.Web.Admin
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        private DataSet ds;
        protected void Button1_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            DateTime startdate = DateTime.Now.AddDays(1 - DateTime.Now.Day);//FirstDayOfPreviousMonth(DateTime.Now.Date);
            BLL.statistics sta = new BLL.statistics();

            string show = "";
            for (DateTime d = startdate; d <= DateTime.Now.Date; d = d.AddDays(1))
            {
                if (sta.Exists(d) == false)
                {


                    ListBox1.Items.Add(d.ToShortDateString());
                    Button5.Visible = true;
                }
            }
            Response.Write(show);
        }
        /// <summary>
        /// 上个月第一天
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        private DateTime FirstDayOfPreviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("date");
            dt.Columns.Add("banmian");
            dt.Columns.Add("title");
            dt.Columns.Add("txtnum");
            dt.Columns.Add("txtoauth");
            dt.Columns.Add("imgnum");
            dt.Columns.Add("imgoauth");
            dt.Columns.Add("isnew");
            dt.Columns.Add("url");
            dt.Columns.Add("isshow", Type.GetType("System.Boolean"));
            dt.Columns.Add("btname");
            ds.Tables.Add(dt);
            string url = TextBox1.Text.Trim();
            if (!url.EndsWith("\\"))
                url += "\\";

            for (int i = 0; i < ListBox1.Items.Count; i++)
            {
                DateTime d = Convert.ToDateTime(ListBox1.Items[i].Text);

                string u = string.Format("{0}-{1}\\{2}", d.Year.ToString().PadLeft(4, '0'), d.Month.ToString().PadLeft(2, '0'), d.Day.ToString().PadLeft(2, '0'));
                string ur = url + u + "\\";
                string ul = ur + "node_3.htm";
                if (!ul.StartsWith("http://"))
                {
                    if (!File.Exists(ul))
                        continue;

                    StreamReader sr = new StreamReader(ul);
                    string node = sr.ReadToEnd();
                    sr.Close();
                    Regex r = new Regex("<a href=(?<url>node_[0-9]{1,2}.htm) class=\"blue\" id=pageLink>(?<title>[^ <> ]*)</a>");
                    MatchCollection ms = r.Matches(node);
                    foreach (Match m in ms)
                    {
                        GroupCollection gs = m.Groups;
                        string nodeurl = gs["url"].Value;//板块连接
                        string banmian = gs["title"].Value;//板块

                        ul = ur + nodeurl;

                        sr = new StreamReader(ul);
                        node = sr.ReadToEnd();
                        sr.Close();

                        Regex pager = new Regex("<a href=[./]*(?<pageurl>content_[0-9]*.htm)>(?<pagetile>[^ <> ]*[<BR/> ]*[^ <> ]*)</a> ");
                        MatchCollection page = pager.Matches(node);

                        foreach (Match p in page)
                        {
                            GroupCollection pagegcs = p.Groups;

                            string pageurl = pagegcs["pageurl"].Value;
                            string pagetile = pagegcs["pagetile"].Value;
                            ul = ur + pageurl;
                            sr = new StreamReader(ul);
                            node = sr.ReadToEnd();
                            node = node.ToLower();
                            node = node.Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace(" ", "");
                            int star = node.IndexOf("<tdclass=\"xilan_content_tt\">");
                            int end = node.IndexOf("</td>", star + 30);
                            string contenthtml = node.Substring(star + 30, end - star);//获取新闻内容
                            string content = "";
                            string txtoauth = "-";
                            string isnew = "-";//新作者
                            Regex conre = new Regex("<p>[^ <> ]*</p>");//获取文本字数
                            MatchCollection con = conre.Matches(contenthtml);
                            BLL.users user = new BLL.users();

                            foreach (Match c in con)
                            {
                                if (c.Value.Contains("本报记者") || c.Value.Contains("本报讯"))
                                {
                                    //Regex rx = new Regex("本报[^<>]*[&nbsp;]*[（]*(?<author>[^<>&nbsp;]*)[摄]*[）]*[&nbsp;]*");
                                    //MatchCollection mx = rx.Matches(c.Value);
                                    //foreach (Match mm in mx)
                                    //{
                                    //    GroupCollection scc = mm.Groups;
                                    //    string mstr = scc["author"].Value;
                                    //}
                                    if (c.Value.Contains("本报讯") && c.Value.Contains("（"))
                                    {
                                        int ss = c.Value.IndexOf("（");
                                        int ee = c.Value.IndexOf("）", ss);
                                        txtoauth = c.Value.Substring(ss, ee - ss);
                                    }
                                    else
                                    {
                                        txtoauth = c.Value;
                                    }
                                    txtoauth = txtoauth.Replace("<p>", "");
                                    txtoauth = txtoauth.Replace("</p>", "");
                                    string[] sub = txtoauth.Split(new string[] { "&nbsp;" }, StringSplitOptions.RemoveEmptyEntries);
                                    txtoauth = "";
                                    isnew = "";
                                    foreach (string s in sub)
                                    {
                                        if (!s.Contains("本报") && !s.Contains("摄") && !s.Contains("图") && s != "文" && !s.Contains("记者") && !s.Contains("通讯员") && s.Length <= 10)
                                        {

                                            if (!user.Exists(s))
                                                isnew += s + "|";
                                            txtoauth += s + "|";

                                        }

                                    }
                                }
                                content += c.Value.Trim();
                            }
                            content = content.Replace("&nbsp;", "");
                            content = content.Replace("<p>", "");
                            content = content.Replace("</p>", "");
                            int txtnum = content.Length;
                            //int imgstart = node.IndexOf("<table bgcolor=#efefef>");//

                            string imgoauth = "-";
                            int imgnum = 0;
                            //if (imgstart > 0)
                            //{
                            //imgstart = imgstart + 24;
                            //int imgend = node.IndexOf("</table>", imgstart);

                            //string imghtml = node.Substring(imgstart, imgend - imgstart);
                            //Regex imgre = new Regex("<imgsrc=[\"]?../../../res/[/a-z0-9_.-]*[\"]?>");//图片html
                            Regex imgre = new Regex("<imgsrc=[\"]?../../../res/[/a-z0-9_.-]*[\"]?>");//图片html
                            MatchCollection imgs = imgre.Matches(node);
                            imgnum = imgs.Count;

                            foreach (Match im in imgs)
                            {
                                GroupCollection ig = im.Groups;
                                string imgtitle = ig["imgtitle"].Value;
                                if (imgtitle.Contains("本报"))
                                {
                                    string[] sub = imgtitle.Split(new string[] { "&nbsp;" }, StringSplitOptions.RemoveEmptyEntries);
                                    imgoauth = "";
                                    foreach (string s in sub)
                                    {
                                        if (!s.Contains("本报") && !s.Contains("摄"))
                                        {
                                            string oauth = s.Trim(new char[] { '）', '（', '(', ')' });
                                            if (!user.Exists(oauth))
                                                isnew += oauth + "|";
                                            imgoauth += s.Trim(new char[] { '）', '（', '(', ')' }) + "|";
                                        }
                                    }
                                }
                            }

                            string btname = "忽略";
                            bool isshow = true;
                            if (!CheckBox1.Checked)//忽略新记者
                            {
                                btname = "添加新记者";
                                isshow = false;
                            }
                            txtoauth = txtoauth.Trim(new char[] { '|' }).Trim(new char[] { '）', '（', '(', ')' }); ;

                            imgoauth = imgoauth.Trim(new char[] { '|' }).Trim(new char[] { '）', '（', '(', ')' }); ;
                            isnew = isnew.Trim(new char[] { '|' }).Trim(new char[] { '）', '（', '(', ')' }); ;
                            if (!((txtoauth == "-" || txtoauth == "") && (imgoauth == "-" || imgoauth == "") && CheckBox2.Checked))//不忽略无作者
                            {
                                dt.Rows.Add(d.ToShortDateString(), banmian, pagetile, txtnum.ToString(), txtoauth, imgnum.ToString(), imgoauth, isnew, ul, isshow, btname);
                            }

                        }
                    }
                }
            }
            if (ds == null || ds.Tables.Count == 0)
                return;
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }

        protected void Button3_Click(object sender, EventArgs e)
        {

        }

        protected void Button4_Click(object sender, EventArgs e)
        {

        }

        protected void Button5_Click(object sender, EventArgs e)
        {
            ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("date");
            dt.Columns.Add("banmian");
            dt.Columns.Add("title");
            dt.Columns.Add("txtnum");
            dt.Columns.Add("txtoauth");
            dt.Columns.Add("imgnum");
            dt.Columns.Add("imgoauth");
            dt.Columns.Add("isnew");
            dt.Columns.Add("url");
            dt.Columns.Add("isshow", Type.GetType("System.Boolean"));
            dt.Columns.Add("btname");
            dt.Columns.Add("index");
            ds.Tables.Add(dt);
            string url = TextBox1.Text.Trim();
            if (!url.EndsWith("\\"))
                url += "\\";
            int index = 0;
            for (int i = 0; i < ListBox1.Items.Count; i++)
            {
                DateTime d = Convert.ToDateTime(ListBox1.Items[i].Text);

                string u = string.Format("{0}-{1}\\{2}", d.Year.ToString().PadLeft(4, '0'), d.Month.ToString().PadLeft(2, '0'), d.Day.ToString().PadLeft(2, '0'));
                string ur = url + u + "\\";
                DirectoryInfo contentpagelist = new DirectoryInfo(ur);
                string ul = "";
                StreamReader sr;
                string node = "";
                if (!Directory.Exists(ur))
                    continue;
                foreach (FileInfo file in contentpagelist.GetFiles("content_*.htm"))
                {
                    // Console.WriteLine(file.FullName);
                    ul = ConfigurationManager.AppSettings["url"].ToString()+u+"/"+file.Name;

                    sr = new StreamReader(file.FullName);
                    node = sr.ReadToEnd().Trim();
                    if (node == "")
                        continue;
                    node = node.ToLower();
                    node = node.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
                    int contentstartindex = node.IndexOf("<founder-content>") + "<founder-content>".Length;
                    int contentendindex = node.IndexOf("</founder-content>");
                    string content = node.Substring(contentstartindex, contentendindex - contentstartindex);
                    if (content == "<p></p>"||content=="")
                        continue;
                    int titlestartindex = node.IndexOf("<td class=\"bt1\" align=center>") + "<td class=\"bt1\" align=center>".Length;
                    int titleendindex = node.IndexOf("</td>", titlestartindex);
                    string title = node.Substring(titlestartindex, titleendindex - titlestartindex);
                    string[] jizhe = null;
                    BLL.users user = new BLL.users();
                    string isnew = "";
                    string txtoauth = "";
                    BLL.users us = new BLL.users();
                    Model.users usmod = new Model.users();
                    usmod.assessmentid = int.Parse(TextBox2.Text);
                    if (content.Contains("本报讯（"))
                    {
                        int jizhestart = content.IndexOf("本报讯（") + "本报讯（".Length;
                        int jizheend = content.IndexOf("）", jizhestart);
                        string tmp = content.Substring(jizhestart, jizheend - jizhestart);
                        jizhe = tmp.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                    }
                    else
                        if (content.Contains("本报记者"))
                        {
                            int jizhestart = content.IndexOf("本报记者") + "本报记者".Length;
                            int jizheend = content.IndexOf("</p>", jizhestart);
                            string tmp = content.Substring(jizhestart, jizheend - jizhestart);
                            jizhe = tmp.Split(new string[] { "&nbsp;" }, StringSplitOptions.RemoveEmptyEntries);
                        }
                        else
                        {
                            int jizhestart = content.LastIndexOf("<p>") + "<p>".Length;
                            int jizheend = content.IndexOf("</p>", jizhestart);
                            string tmp = content.Substring(jizhestart, jizheend - jizhestart);
                            jizhe = tmp.Split(new string[] { "&nbsp;" }, StringSplitOptions.RemoveEmptyEntries);
                        }
                    if (jizhe != null)
                    {
                        foreach (string j in jizhe)
                        {
                            if (!j.Contains("记者") && !j.Contains("据") && !j.Contains("年") && !j.Contains("日") && !j.Contains("-") && !j.Contains("版") && !j.Contains("通讯员") && !j.Contains("摄") && !j.Contains("月") && !j.Contains("文") && !j.Contains("图") && !j.Contains("期") && !j.Contains("本报") && j.Length < 8)
                            {
                                txtoauth += j + "|";
                                if (!user.Exists(j))
                                {
                                    isnew += j + "|";
                                    if (CheckBox3.Checked)
                                    {
                                        usmod.name = j;
                                        usmod.payinfo = "";
                                        usmod.permisscode = "0005";
                                        usmod.permissname = "记者";
                                        usmod.phone = "";
                                        usmod.pwd = "123456";
                                        us.Add(usmod);
                                    }
                                }
                            }
                        }
                    }
                    content = content.Replace("&nbsp;", "");
                    content = content.Replace("<p>", "");
                    content = content.Replace("</p>", "");
                    int txtnum = content.Length;
                    string imgoauth = "-";
                    int imgnum = 0;
                    Regex imgre = new Regex("<imgsrc=[\"]?../../../res/[/a-z0-9_.-]*[\"]?>");//图片html
                    MatchCollection imgs = imgre.Matches(node);
                    imgnum = imgs.Count;
                    string btname = "忽略";
                    bool isshow = true;
                    if (!CheckBox3.Checked)
                    {
                        if (CheckBox1.Checked)//忽略新记者并没添加新记者
                        {
                            btname = "忽略";
                            isshow = true;
                        }
                        else
                        {
                            if (isnew != "")
                            {
                                btname = "添加新记者";
                                isshow = false;
                            }
                        }
                    }
                    txtoauth = txtoauth.Trim(new char[] { '|' }).Trim(new char[] { '）', '（', '(', ')' }); 

                    imgoauth = imgoauth.Trim(new char[] { '|' }).Trim(new char[] { '）', '（', '(', ')' }); 
                    isnew = isnew.Trim(new char[] { '|' }).Trim(new char[] { '）', '（', '(', ')' }); 
                    if (!((txtoauth == "-" || txtoauth == "") && (imgoauth == "-" || imgoauth == "") && CheckBox2.Checked))//不忽略无作者
                    {
                        dt.Rows.Add(d.ToShortDateString(), "未知", title, txtnum.ToString(), txtoauth, imgnum.ToString(), imgoauth, isnew, ul, isshow, btname,index);
                        index++;
                    }
                  
                }
            }

            if (ds == null || ds.Tables.Count == 0)
                return;
            GridView1.DataSource = ds;
            GridView1.DataBind();
            if(CheckBox3.Checked)
                Page.RegisterStartupScript("success", "<script>alert('新记者已经入库完毕，无须再添加！')</script>");
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "add")
            {
                Button add = (Button)e.CommandSource;
                if (add.Text=="添加新记者")
                {
                    BLL.users us = new BLL.users();
                    Model.users usmod = new Model.users();
                    usmod.assessmentid = int.Parse(TextBox2.Text);
                    string[] name = e.CommandArgument.ToString().Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    if (name.Length > 0)
                    {
                        foreach (string j in name)
                        {
                            usmod.name = j;
                            usmod.payinfo = "";
                            usmod.permisscode = "0005";
                            usmod.permissname = "记者";
                            usmod.phone = "";
                            usmod.pwd = "123456";

                            us.Add(usmod);

                        }
                        Page.RegisterStartupScript("success", "<script>alert('添加成功！')</script>");
                        Button5_Click(null,null);
                       
                    }
                    else
                    { }
                }
            }
            else
                if (e.CommandName == "insert")
                {
                    BLL.users u = new BLL.users();
                    BLL.statistics bllsta = new BLL.statistics();
                    int index = Convert.ToInt32(e.CommandArgument);
                    string title = GridView1.Rows[index].Cells[3].Text;
                    string txtnum = GridView1.Rows[index].Cells[4].Text;
                    string imgnum = GridView1.Rows[index].Cells[6].Text;
                    string[] jizhe = GridView1.Rows[index].Cells[5].Text.Replace("&nbsp;","").Split(new char[] { '|' },StringSplitOptions.RemoveEmptyEntries);
                    if (jizhe.Length > 0)
                    {
                        foreach (string s in jizhe)
                        {
                            int userid = u.getid(s);
                            if (userid > 0)
                            {
                                Model.statistics sta = new Model.statistics();
                                sta.date = DateTime.Now.ToShortDateString();
                                sta.imgnum = Convert.ToInt32( imgnum);
                                sta.isverify = 0;
                                sta.other = "";
                                sta.title = title;
                                sta.userid = userid;
                                sta.verifyid =Convert.ToInt32( Session["userid"]);
                                sta.wordnum =Convert.ToInt32( txtnum);
                                bllsta.Add(sta);
                            }
                        }
                        ((Button)GridView1.Rows[index].Cells[10].FindControl("Button4")).Visible = false;
                        Page.RegisterStartupScript("success", "<script>alert('审核成功！')</script>");
                        
                    }
                    else
                        Page.RegisterStartupScript("success", "<script>alert('无记者，不需要审核！')</script>");
                }

        }
    }
}